//
//  ZiDingYiXuanChengYuanViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/17.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "ZiDingYiXuanChengYuanViewController.h"
#import "ZiDingYiXuanChengYuanTableViewCell.h"
#import "ZiDingYiXuanChengYuanCollectionViewCell.h"
#import "BMChineseSort.h"
#import "ChaKanYiXuanChengYanView.h"
@interface ZiDingYiXuanChengYuanViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{

    NSArray *orignArray;
    NSMutableArray *buMenArray;
    NSMutableArray *chengYuanArray;
    
    NSMutableDictionary *dataSourceDictionary;
    
    NSMutableArray *collectionViewDataSource;
    
    NSMutableArray *souSuoArray;
}
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (weak, nonatomic) IBOutlet UICollectionView *mainCollectionView;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UITextField *searchTextView;
@property (weak, nonatomic) IBOutlet UILabel *yiXuanBuMenNumLabel;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineViewHeight;
@property (weak, nonatomic) IBOutlet UIView *searchBackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchViewHeight;

@end

@implementation ZiDingYiXuanChengYuanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.customNavBar.title = @"请选择";
    
    _topSpace.constant = NavaBarHeight;
    
    CGFloat radius = 10; // 圆角值大小
    if (@available(iOS 11.0, *)){
        // 设置 左上 右上 圆角
        _bottomView.layer.cornerRadius = radius;
        _bottomView.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    }else {
        // 设置 左上 右上 圆角
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0,0,ScreenWidth,195) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(radius, radius)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = CGRectMake(0,0,ScreenWidth,195);
        maskLayer.path = path.CGPath;
        _bottomView.layer.mask = maskLayer;
    }

    _bottomView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1600].CGColor;
    _bottomView.layer.shadowOffset = CGSizeMake(2,0);
    _bottomView.layer.shadowOpacity = 1;
    _bottomView.layer.shadowRadius = 10;
    
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        self.mainTableView.sectionHeaderTopPadding = 0 ;
    } else {
        // Fallback on earlier versions
    }
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"ZiDingYiXuanChengYuanTableViewCell" bundle:nil] forCellReuseIdentifier:@"ZiDingYiXuanChengYuanTableViewCell"];


    buMenArray = [NSMutableArray array];
    
    chengYuanArray = [NSMutableArray array];
    
    [_mainCollectionView registerNib:[UINib nibWithNibName:@"ZiDingYiXuanChengYuanCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ZiDingYiXuanChengYuanCollectionViewCell"];
    
    [_searchTextView addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    if(_type == 1){
        //        选部门
        _searchBackView.hidden = YES;
        _searchViewHeight.constant = 0;
        _lineView.hidden = YES;
        _lineViewHeight.constant = 0;
        
        _yiXuanBuMenNumLabel.text = @"已选择：0部门";
    }else if(_type == 2){
        //        选成员
        _yiXuanBuMenNumLabel.text = @"已选择：0人";
    }
    
    [self huoQuDiYiCengJi];
    
    [self huoQuQuanBuChengYuan];
    
    // 创建一个手势识别器
       UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]
                                              initWithTarget:self
                                              action:@selector(dismissKeyboard:)];
       
       // 设置手势识别器不取消视图中的触摸
       tapGesture.cancelsTouchesInView = NO;
//       tapGesture.delaysTouchesBegan = YES;
       // 将手势识别器添加到view
       [self.view addGestureRecognizer:tapGesture];
}

- (void)dismissKeyboard:(UITapGestureRecognizer *)recognizer {
    CGPoint location = [recognizer locationInView:self.mainTableView];
    NSIndexPath *indexPath = [self.mainTableView indexPathForRowAtPoint:location];

    if (!indexPath) {
        // 点击的不是UITableViewCell，收起键盘
        [self.view endEditing:YES];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

//获取所有用户用于查询用户
- (void)huoQuQuanBuChengYuan{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@"0" forKey:@"pageType"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/adminUser/queryUserList" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
        
            NSDictionary *dataDic = [info objectForKey:@"data"];
            
            orignArray = [dataDic objectForKey:@"list"];
        
        }
    }];
}
//获取一级成员
- (void)huoQuDiYiCengJi{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@"tree" forKey:@"type"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/adminDept/queryDeptTree" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            NSArray *array = [info objectForKey:@"data"];
            if([array count] > 0){
                collectionViewDataSource = [NSMutableArray array];
                NSMutableDictionary *temp = [NSMutableDictionary dictionary];
                [temp setValue:GetHandleString(array.firstObject, @"deptId") forKey:@"deptId"];
                [temp setValue:@"全部" forKey:@"name"];
                [temp setValue:@"1" forKey:@"hasChildren"];
                [collectionViewDataSource
                 addObject:temp];
                [_mainCollectionView reloadData];

                dataSourceDictionary = [NSMutableDictionary dictionary];
                NSMutableArray *tempArray = [NSMutableArray array];
                NSMutableDictionary *tempD = [NSMutableDictionary dictionaryWithDictionary:array.firstObject];
                [tempD setValue:@"1" forKey:@"hasChildren"];
                [tempArray addObject:tempD];
                [dataSourceDictionary setValue:tempArray forKey:@"deptList"];
                [dataSourceDictionary setValue:[NSArray array] forKey:@"userList"];
                
                [_mainTableView reloadData];
            }
        }
    }];
}
//根据部门id获取下属部门与当前部门用户接口
- (void)huoQuQiTaCengJiWithDeptid:(NSString *)deptId{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@"tree" forKey:@"type"];
    
    NSString *url = [NSString stringWithFormat:@"/adminUser/queryDeptUserList/%@",deptId];
    
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:url andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            NSLog(@"info:%@",info);
            dataSourceDictionary = [NSMutableDictionary dictionaryWithDictionary:[info objectForKey:@"data"]];
            [_mainTableView reloadData];
        }
    }];
}


- (void)textFieldDidChange:(UITextField *)textField{
    if(textField.text.length > 0){
        _headerView.frame  = CGRectMake(0, 0, ScreenWidth, 0);
        _headerView.hidden = YES;
        
        souSuoArray = [NSMutableArray array];
        for (NSDictionary *dataDic in orignArray) {
            if([GetHandleString(dataDic, @"realname") containsString:textField.text]){
                [souSuoArray addObject:dataDic];
            }
        }
    }else{
        _headerView.frame  = CGRectMake(0, 0, ScreenWidth, 76);
        _headerView.hidden = NO;
    }
    [_mainTableView reloadData];
}






-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(_searchTextView.text.length > 0){
        return 1;
    }
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_searchTextView.text.length > 0){
        return souSuoArray.count;
    }
    if(section == 0){
        
        return [[dataSourceDictionary objectForKey:@"deptList"] count];
    }
    
//    在只选部门的情况下 员工不展示
    if(_type == 1){
        return 0;
    }
    return [[dataSourceDictionary objectForKey:@"userList"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ZiDingYiXuanChengYuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZiDingYiXuanChengYuanTableViewCell"];
    if(_searchTextView.text.length > 0){
        cell.rightButton.hidden = YES;
        cell.leftSpace.constant = 20-5;
        cell.selectButton.hidden = NO;
        NSDictionary *dataDic = souSuoArray[indexPath.row];
        cell.nameLabel.text = GetHandleString(dataDic, @"realname");
        cell.selectButton.selected = [self shiFouCunZaiObjetName:@"userId" andArray:chengYuanArray andValue:GetHandleString(dataDic, @"userId")];
        cell.selectClickBlock = ^(UIButton * _Nonnull btn) {
            if(_type == 2){
               //只选成员
                chengYuanArray = [NSMutableArray array];
                [chengYuanArray addObject:dataDic];
               _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld人",chengYuanArray.count];
            }else{
                NSDictionary *xuanZhongDic = nil;
                for (NSDictionary *temp in chengYuanArray) {
                    if([GetHandleString(temp, @"userId") isEqualToString:GetHandleString(dataDic, @"userId")]){
                        xuanZhongDic = temp;
                        break;
                    }
                }
                
                if(xuanZhongDic != nil){
                    [chengYuanArray removeObject:xuanZhongDic];
                }else{
                    [chengYuanArray addObject:dataDic];
                }
                
                _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld人，%ld部门",chengYuanArray.count,buMenArray.count];
            }
            [UIView performWithoutAnimation:^{
                [_mainTableView reloadData];
            }];
        };
        
        
        return cell;
    }
    
    cell.leftSpace.constant = 32-5;
    
    if(indexPath.section == 0){
        NSDictionary *dataDic = [dataSourceDictionary objectForKey:@"deptList"][indexPath.row];
        cell.nameLabel.text = [NSString stringWithFormat:@"%@（%@人）",GetHandleString(dataDic, @"name"),GetHandleString(dataDic, @"currentNum")];
        cell.rightButton.hidden = NO;
        cell.rightButton.selected = [self shiFouCunZaiObjetName:@"deptId" andArray:buMenArray andValue:GetHandleString(dataDic, @"deptId")];
        cell.selectButton.selected = [self shiFouCunZaiObjetName:@"deptId" andArray:buMenArray andValue:GetHandleString(dataDic, @"deptId")];
        
        if(_type == 2){
//            只选员工
            cell.leftSpace.constant = 4;
            cell.selectButton.hidden = YES;
        }else{
            cell.leftSpace.constant = 32-5;
            cell.selectButton.hidden = NO;
        }
        
        
        cell.selectClickBlock = ^(UIButton * _Nonnull btn) {
            if(btn.selected){
                [buMenArray removeObject:dataDic];
            }else{
                [buMenArray addObject:dataDic];
            }
            //    在只选部门的情况下 员工不展示
                if(_type == 1){
                    _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld部门",buMenArray.count];
                }else{
                    _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld人，%ld部门",chengYuanArray.count,buMenArray.count];
                }
            
            [UIView performWithoutAnimation:^{
                [_mainTableView reloadData];
            }];
        };
        
    }else{
        cell.leftSpace.constant = 32-5;
        cell.selectButton.hidden = NO;
        
        NSDictionary *dataDic = [dataSourceDictionary objectForKey:@"userList"][indexPath.row];
        cell.nameLabel.text = GetHandleString(dataDic, @"realname");
        cell.rightButton.hidden = YES;
        cell.selectButton.selected = [self shiFouCunZaiObjetName:@"userId" andArray:chengYuanArray andValue:GetHandleString(dataDic, @"userId")];
        
        
        cell.selectClickBlock = ^(UIButton * _Nonnull btn) {
            
             if(_type == 2){
                //只选成员
                 chengYuanArray = [NSMutableArray array];
                 [chengYuanArray addObject:dataDic];
                _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld人",chengYuanArray.count];
             }else{
                 NSDictionary *xuanZhongDic = nil;
                 for (NSDictionary *temp in chengYuanArray) {
                     if([GetHandleString(temp, @"userId") isEqualToString:GetHandleString(dataDic, @"userId")]){
                         xuanZhongDic = temp;
                         break;
                     }
                 }
                 if(xuanZhongDic != nil){
                     [chengYuanArray removeObject:xuanZhongDic];
                 }else{
                     NSMutableDictionary *resDic = [NSMutableDictionary dictionaryWithDictionary:dataDic];
                     [resDic setValue:GetHandleString(collectionViewDataSource.lastObject, @"name") forKey:@"deptName"];
                     [chengYuanArray addObject:resDic];
                 }
                 
                 _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld人，%ld部门",chengYuanArray.count,buMenArray.count];
             }
          
            [UIView performWithoutAnimation:^{
                [_mainTableView reloadData];
            }];
        };
        
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];

    if(indexPath.section == 0 && _searchTextView.text.length == 0){
        NSDictionary *dataDic = [dataSourceDictionary objectForKey:@"deptList"][indexPath.row];
        if(![self shiFouCunZaiObjetName:@"deptId" andArray:buMenArray andValue:GetHandleString(dataDic, @"deptId")]){
            [self huoQuQiTaCengJiWithDeptid:GetHandleString(dataDic, @"deptId")];
            [collectionViewDataSource addObject:dataDic];
            [_mainCollectionView reloadData];
            NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:collectionViewDataSource.count-1 inSection:0];
            [_mainCollectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
        }
    }

}

//判断是否已选
- (BOOL)shiFouCunZaiObjetName:(NSString *)name andArray:(NSArray *)array andValue:(NSString *)value{
    BOOL isHave = NO;
    for (NSDictionary *dataDic in array) {
        if([GetHandleString(dataDic, name) isEqualToString:value]){
            isHave = YES;
            break;
        }
    }
    return isHave;
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return collectionViewDataSource.count;
}
//创建cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZiDingYiXuanChengYuanCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZiDingYiXuanChengYuanCollectionViewCell" forIndexPath:indexPath];
    NSDictionary *dataDic = collectionViewDataSource[indexPath.row];
    if(indexPath.row == 0 && collectionViewDataSource.count == 1){
        cell.backImage.image = LocalImagePath(@"选择联系人1");
    }else{
        if(indexPath.row == 0){
            cell.backImage.image = LocalImagePath(@"选择联系人2");
        }else{
            
            if(indexPath.row == collectionViewDataSource.count-1){
//                if([GetHandleString(dataDic, @"hasChildren") boolValue] == 1){
//                    cell.backImage.image = LocalImagePath(@"电邀一组1");
//                }else{
//                    cell.backImage.image = LocalImagePath(@"电邀一组1");
//                }
                cell.backImage.image = LocalImagePath(@"电邀一组1");
            }else{
                cell.backImage.image = LocalImagePath(@"电邀部2");
            }
        }
    }
    
    cell.nameLabel.text = GetHandleString(dataDic, @"name");

    return cell;
}





//设置item的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(120, 36);
}
//设置垂直间距,默认的垂直和水平间距都是10
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return -10;
}
//设置水平间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

//四周的边距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(20, 16, 20, 16);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if(indexPath.row == 0){
        [self huoQuDiYiCengJi];
    }else{
        NSDictionary *dataDic = collectionViewDataSource[indexPath.row];
        if(indexPath.row != collectionViewDataSource.count-1){
            [self huoQuQiTaCengJiWithDeptid:GetHandleString(dataDic, @"deptId")];
            [collectionViewDataSource removeObjectsInRange:NSMakeRange(indexPath.row+1, collectionViewDataSource.count-1-indexPath.row)];
            [_mainCollectionView reloadData];
            NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:collectionViewDataSource.count-1 inSection:0];
            [_mainCollectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
            
        }
    }
}

//查看已选成员
- (IBAction)chaKanYiXuan:(UIButton *)sender {
    ChaKanYiXuanChengYanView *chaKan = [ChaKanYiXuanChengYanView view];
    chaKan.firstArray = [NSMutableArray arrayWithArray:buMenArray];
    chaKan.secondArray = [NSMutableArray arrayWithArray:chengYuanArray];
    chaKan.titleLabel.text = _yiXuanBuMenNumLabel.text;
    chaKan.shaiXuanYiXuanNumLabel.text = _yiXuanBuMenNumLabel.text;
    chaKan.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
        if(index == 103){
//            确定
            
            [self dianJiQuRenClick:nil];
        }
    };
    
    
    chaKan.removeObjectClickBlock = ^(NSArray * _Nonnull resultArray, BOOL isFirst) {
        if(isFirst){
            buMenArray = [NSMutableArray arrayWithArray:resultArray];
        }else{
            chengYuanArray = [NSMutableArray arrayWithArray:resultArray];
        }
        [UIView performWithoutAnimation:^{
            [_mainTableView reloadData];
        }];
        //    在只选部门的情况下 员工不展示
            if(_type == 1){
                _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld部门",buMenArray.count];
            }else if(_type == 2){
                //只选成员
                _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld人",chengYuanArray.count];
            }else{
                _yiXuanBuMenNumLabel.text = [NSString stringWithFormat:@"已选择：%ld人，%ld部门",chengYuanArray.count,buMenArray.count];
            }
    };
    
    
    [ZZPUtils showActionSheetWithView:chaKan andController:self];
}

//确认
- (IBAction)dianJiQuRenClick:(UIButton *)sender {
    
    if(_manageResultBlock){
        _manageResultBlock(chengYuanArray,buMenArray);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无搜索"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无数据~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName: rgba(163, 168, 185, 1)}];
    return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



